from flask import Blueprint, request, jsonify
from .. import db
from app.models.Order import Order
from app.models.User import User
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.utils.response import success_api, fail_api
from app.utils.validator import validate_params
import uuid
from datetime import datetime
from ..base import base

# 获取订单列表
@base.route('/order/list', methods=['GET'])
@jwt_required()
def get_order_list():
    try:
        # 获取查询参数
        order_no = request.args.get('orderNo')
        shop_id = request.args.get('shopId')
        product_id = request.args.get('productId')
        order_status = request.args.get('orderStatus')
        start_time = request.args.get('startTime')
        end_time = request.args.get('endTime')
        page_num = int(request.args.get('pageNum', 1))
        page_size = int(request.args.get('pageSize', 10))

        # 构建查询条件
        query = Order.query.join(Order.product).join(Order.user)
        if order_no:
            query = query.filter(Order.order_no == order_no)
        if shop_id:
            query = query.filter(Order.shop_id == shop_id)
        if product_id:
            query = query.filter(Order.product_id == product_id)
        if order_status:
            query = query.filter(Order.order_status == order_status)
        if start_time:
            query = query.filter(Order.create_time >= start_time)
        if end_time:
            query = query.filter(Order.create_time <= end_time)

        # 分页查询
        total = query.count()
        orders = query.order_by(Order.create_time.desc()).offset((page_num - 1) * page_size).limit(page_size).all()
        
        # 返回结果
        return success_api({
            'total': total,
            'rows': [order.to_dict()  for order in orders]
        })
    except Exception as e:
        return fail_api(msg=str(e))

# 获取订单详情
@base.route('/order/<order_id>', methods=['GET'])
@jwt_required()
def get_order(order_id):
    try:
        order = Order.query.get(order_id)
        if not order:
            return fail_api(msg='订单不存在')
        return success_api(data=order.to_dict())
    except Exception as e:
        return fail_api(msg=str(e))

# 创建订单
@base.route('/order', methods=['POST'])
@jwt_required()
def create_order():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['shopId', 'productId', 'userId', 'amount']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 创建订单对象
        order = Order(
            order_id=str(uuid.uuid4()),
            order_no=f'O{datetime.now().strftime("%Y%m%d%H%M%S")}{str(uuid.uuid4())[:8]}',
            shop_id=data.get('shopId'),
            product_id=data.get('productId'),
            user_id=data.get('userId'),
            amount=data.get('amount'),
            order_status='0',  # 初始状态：待支付
            remark=data.get('remark')
        )

        # 保存到数据库
        db.session.add(order)
        db.session.commit()

        return success_api(msg='创建成功', data={'orderId': order.order_id})
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 更新订单状态
@base.route('/order/status', methods=['PUT'])
@jwt_required()
def update_order_status():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['orderId', 'orderStatus']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 查询订单
        order = Order.query.get(data.get('orderId'))
        if not order:
            return fail_api(msg='订单不存在')

        # 更新订单状态
        order.order_status = data.get('orderStatus')
        order.update_time = datetime.now()

        # 保存到数据库
        db.session.commit()

        return success_api(msg='状态更新成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 取消订单
@base.route('/order/cancel/<order_id>', methods=['PUT'])
@jwt_required()
def cancel_order(order_id):
    try:
        order = Order.query.get(order_id)
        if not order:
            return fail_api(msg='订单不存在')

        # 检查订单状态是否可以取消
        if order.order_status != '0':
            return fail_api(msg='当前订单状态不可取消')

        # 更新订单状态为已取消
        order.order_status = '9'  # 9表示已取消
        order.update_time = datetime.now()

        # 保存到数据库
        db.session.commit()

        return success_api(msg='订单取消成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))